﻿using JetBrains.Annotations;
using System;
using System.Threading;

namespace Loong
{
    public class DisposeAction : IDisposable
    {
        public static readonly DisposeAction Empty = new DisposeAction(null);

        private Action _action;

        public DisposeAction([CanBeNull] Action action)
        {
            _action = action;
        }

        private bool _disposed;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;

            if (disposing)
            {
                // Interlocked prevents multiple execution of the _action.
                var action = Interlocked.Exchange(ref _action, null);
                action?.Invoke();
            }

            _disposed = true;
        }
    }
}
